package com.muyi.biling.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Build;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.muyi.biling.biz.JsBridgeHelper;
import com.muyi.biling.util.Utils;

/**
 * Created by developer on 18-2-7.
 */

public class WebViewManager {

    private Activity mActivity;
    private BridgeWebView mWebView;
    private WebSettings mWebSettings;
    private JsBridgeHelper mJsBridgeHelper;

    public WebViewManager(Activity mActivity, BridgeWebView mWebView) {
        this.mActivity = mActivity;
        this.mWebView = mWebView;
        mWebSettings = mWebView.getSettings();

        init();
    }

    private void init() {
        enableJavaScript();
        enableJavaScriptOpenWindowsAutomatically();
        disableZoom();
        enableAdaptive();

        if(Build.VERSION.SDK_INT >= 19) {
            mWebSettings.setLoadsImagesAutomatically(true);
        } else {
            mWebSettings.setLoadsImagesAutomatically(true);
        }

        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
//        mWebSettings.setPluginsEnabled(true);
        mWebSettings.setPluginState(WebSettings.PluginState.ON);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setDomStorageEnabled(true);
        // 为了加速加载图片使用缓存
        mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        // 取消网页记住密码
        mWebSettings.setSavePassword(false);
        mWebSettings.setSaveFormData(false);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            mWebSettings.setAllowUniversalAccessFromFileURLs(true);
        }else{
            try {
                Class<?> clazz = mWebSettings.getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(mWebSettings, true);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        mWebSettings.setGeolocationEnabled(true);
        String dir = mActivity.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //设置定位的数据库路径
        mWebSettings.setGeolocationDatabasePath(dir);

//        mWebView.clearFormData();
        mWebView.clearHistory();
//        mWebView.clearCache(true);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mWebView.setBackgroundColor(Color.argb(1, 0, 0, 0));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (0 != (mActivity.getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        mWebView.setDefaultHandler(new DefaultHandler());

        mJsBridgeHelper = new JsBridgeHelper(mWebView, mActivity);

    }

    public void resume() {
        mWebView.onResume();
        enableJavaScript();
    }

    public void start() {
        resume();
    }

    public void pause() {
        mWebView.onPause();
    }

    public void stop() {
        mWebView.stopLoading();
        disableJavaScript();
    }

    public void destroy() {
        mWebSettings = null;
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            // 释放资源
            mWebView.destroy();
            mWebView = null;
        }

        mActivity = null;
    }

    public void loadUrl(String url) {
        if (mWebView != null) {
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    return true;
                }
            });

            mWebView.loadUrl(url);
        }
    }

    /**
     * 开启自适应功能
     */
    public WebViewManager enableAdaptive(){
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        return this;
    }

    /**
     * 禁用自适应功能
     */
    public WebViewManager disableAdaptive(){
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        return this;
    }

    /**
     * 开启缩放功能
     */
    public WebViewManager enableZoom(){
        mWebSettings.setSupportZoom(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setBuiltInZoomControls(true);
        return this;
    }

    /**
     * 禁用缩放功能
     */
    public WebViewManager disableZoom(){
        mWebSettings.setSupportZoom(false);
        mWebSettings.setUseWideViewPort(false);
        mWebSettings.setBuiltInZoomControls(false);
        return this;
    }

    /**
     * 开启JavaScript
     */
    @SuppressLint("SetJavaScriptEnabled")
    public WebViewManager enableJavaScript(){
        mWebSettings.setJavaScriptEnabled(true);
        return this;
    }

    /**
     * 禁用JavaScript
     */
    public WebViewManager disableJavaScript(){
        mWebSettings.setJavaScriptEnabled(false);
        return this;
    }

    /**
     * 开启JavaScript自动弹窗
     */
    public WebViewManager enableJavaScriptOpenWindowsAutomatically(){
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        return this;
    }

    /**
     * 禁用JavaScript自动弹窗
     */
    public WebViewManager disableJavaScriptOpenWindowsAutomatically(){
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(false);
        return this;
    }

    public void reload() {
        if (mWebView != null) {
            mWebView.reload();
        }
    }

}
